package se.webbzon.oschi01.nbt;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;

import se.webbzon.oschi01.singleton.Singleton;

public class IntArrayTagFactory extends AbstractTagFactory<int[]> implements Singleton {

	private IntArrayTagFactory() {
		super(Tags.TAG_INT_ARRAY, "TAG_Int_Array");
	}

	@Override public IntArrayTag readTag(String tagName, DataInputStream is) throws IOException {
		int size = is.readInt();
		byte[] data = new byte[4*size];
		is.readFully(data);
		IntBuffer intBuf = ByteBuffer.wrap(data).order(ByteOrder.BIG_ENDIAN).asIntBuffer();
		int[] array = new int[intBuf.remaining()];
		intBuf.get(array);
		return new IntArrayTag(this, tagName, array);
	}

	@Override public void writeTag(Tag<int[]> tag, DataOutputStream dos) throws IOException {
		int[] array = tag.getValue();
		ByteBuffer byteBuf = ByteBuffer.allocate(array.length * 4);
		byteBuf.asIntBuffer().put(array);
		dos.writeInt(array.length);
		dos.write(byteBuf.array());
	}

	@Override public Tag<int[]> createTag(String tagName) {
		return new IntArrayTag(this, tagName, new int[0]);
	}

}
